import queue
import blog_spider
import time
import random
import threading


# do_craw方法用来获取url_queue队列中url的值并爬取url地址对应的html内容并将其放入到html_queue队列中
def do_craw(url_queue: queue.Queue, html_queue: queue.Queue):
    while True:
        url = url_queue.get()
        html = blog_spider.craw(url)
        html_queue.put(html)
        print(threading.current_thread().name, f"craw {url}", "url_queue.size=", url_queue.qsize())
        time.sleep(random.randint(1, 2))


# do_parse方法用来获取爬取的html_queue的html内容并将解析, 将解析的结果写入到文件中
def do_parse(html_queue: queue.Queue, fout):
    while True:
        html = html_queue.get()
        results = blog_spider.parse(html)
        for res in results:
            fout.write(str(res) + "\n")
        print(threading.current_thread().name, f"result.size", len(results), "html_queue.size=", html_queue.qsize())
        time.sleep(random.randint(1, 2))


if __name__ == '__main__':
    url_queue = queue.Queue()
    html_queue = queue.Queue()
    for url in blog_spider.urls:
        url_queue.put(url)
    fout = open("data.txt", "w")
    # 开启三个线程来处理这些爬取html的函数
    for idx in range(3):
        t = threading.Thread(target=do_craw, args=(url_queue, html_queue), name=f"craw{idx}")
        t.start()
    # 开启两个线程解析爬取的html页面的内容
    for idx in range(2):
        t = threading.Thread(target=do_parse, args=(html_queue, fout), name=f"parse{idx}")
        t.start()